const fs = require('fs');
const path = require('path');

// 创建日志目录
const logDir = path.join(process.cwd(), 'logs2');
if (!fs.existsSync(logDir)) {
  fs.mkdirSync(logDir, { recursive: true });
}

// 日志文件路径
const logFilePath = path.join(logDir, 'debug.log');

/**
 * 简单的直接写入文件的日志记录器
 */
const debugLogger = {
  log: function(message, data = null) {
    const timestamp = new Date().toISOString();
    let logEntry = `[${timestamp}] INFO: ${message}\n`;
    
    if (data) {
      try {
        logEntry += `DATA: ${JSON.stringify(data, null, 2)}\n`;
      } catch (e) {
        logEntry += `DATA: [无法序列化的数据] ${e.message}\n`;
      }
    }
    
    logEntry += '-'.repeat(50) + '\n';
    
    try {
      fs.appendFileSync(logFilePath, logEntry);
      console.log(`[DEBUG] ${message}`);
    } catch (error) {
      console.error('写入日志失败:', error);
    }
  },
  
  error: function(message, error = null) {
    const timestamp = new Date().toISOString();
    let logEntry = `[${timestamp}] ERROR: ${message}\n`;
    
    if (error) {
      logEntry += `ERROR: ${error.message || error}\n`;
      if (error.stack) {
        logEntry += `STACK: ${error.stack}\n`;
      }
    }
    
    logEntry += '='.repeat(50) + '\n';
    
    try {
      fs.appendFileSync(logFilePath, logEntry);
      console.error(`[DEBUG ERROR] ${message}`);
    } catch (err) {
      console.error('写入错误日志失败:', err);
    }
  }
};

module.exports = debugLogger; 